var that,
  api = new(require('../../utils/api.js')),
  headimg = api.getimgurl(),
  app = getApp(),
  util = new(require('../../utils/util.js'));

// pages/main/main.js
Page({

  /**
   * 页面的初始数据
   */
  data: {
    classname: -1,
    options: '',
    target: {},
    pagesize: 12,
    headimg: headimg,
    cartids: [],
    currentageindex: 0,
    currentpage: 1,
    length: 0,
    list: [],
    already: !1,
    pageboxshow: !1,
    start:0,
    swiperList: [{
      id: 0,
      url: 'https://ossweb-img.qq.com/images/lol/web201310/skin/big84000.jpg'
    }, {
      id: 1,
      url: 'https://ossweb-img.qq.com/images/lol/web201310/skin/big84001.jpg',
    }, {
      id: 2,
      url: 'https://ossweb-img.qq.com/images/lol/web201310/skin/big39000.jpg'
    }, {
      id: 3,
      url: 'https://ossweb-img.qq.com/images/lol/web201310/skin/big10001.jpg'
    }, {
      id: 4,
      url: 'https://ossweb-img.qq.com/images/lol/web201310/skin/big25011.jpg'
    }],
    hasphone:!1,
    sendshow:!1,
    imglist:[],
    searchinput:'',
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    that = this;
    that.setData({
      options
    },()=>{
      console.log(options,'optionsoptions')
    })
    // let isgetphone=wx.getStorageSync('isgetphone')
    // if(isgetphone){
    //   that.setData({isgetphone,hasphone:!0,sendshow:!1})
    // }
    if (app.logininfo) {
      that.setData({
        currentpage: 1,
        length: 0,
        list: [],
        // cartids: [],
      });
      that.getmain();
    } else {
      util.setwatcher(app, this.afterlogin)
    }
  },
  afterlogin: {
    token: res => {
      that.setData({
        currentpage: 1,
        length: 0,
        list: [],
        cartids: [],
      });
      that.getmain();
    }
    // logininfo: (e) => {
    //   if (e.issuccess == 1) {
    //     wx.hideLoading();
    //     wx.setStorage({
    //       key: 'openid',
    //       data: e.openid,
    //     })
    //     that.getmain();

    //   }
    // }

  },
  inputchange(e){
    console.log(e,'eeeeeee')
    // let {list}= that.data
    if(e.detail.value==''){
      that.setData({list:[]})
      that.getmain();
    }
  },
  toswiperdetail(e){
    console.log(e,'imglistiiiii')
    let {id}=e.currentTarget.dataset
    wx.navigateTo({
      url: '../swiperdetail/swiperdetail?id='+id,
    })
  },
  swiperChange: function (e) {
    //console.log(e.detail.current);
    this.setData({
      swiperCurrent: e.detail.current
    })
  },
  // getPhoneNumber(e){
  //   let {hasphone,sendshow}=that.data
  //   api.getphone({edata:e.detail.encryptedData,iv:e.detail.iv},res=>{
  //     if(res.data.issuccess==1){
  //       let data = JSON.parse(res.data.data);
  //       that.setData({hasphone:!0,sendshow:!1})
  //       console.log(data,'data')
  //       //更新用户手机号
  //     }
  //   })
  // },
  getPhoneNumber(e){
    let {hasphone,sendshow}=that.data
    api.getphone({edata:e.detail.encryptedData,iv:e.detail.iv},res=>{
      if(res.data.issuccess==1){
        let data = JSON.parse(res.data.data);
        let isgetphone=true
        wx.setStorageSync('isgetphone', isgetphone)
        that.setData({hasphone:!0,sendshow:!1,isgetphone})
        console.log(data,'data')
        console.log(data.phoneNumber,'data')
        let phone=data.phoneNumber
        //更新用户手机号
        api.getuserphone(phone,res=>{
          if(res.data.issuccess==1){
            console.log(res.data,'phone')
          }
        })
      }
    })
  },
  editcart(e) {
    let {
      index,
      kc
    } = e.currentTarget.dataset, {
        list,
        cartids
      } = this.data,
      already = !list[index].already,
      cartdatda=list[index],
      ids = list[index].id;
      console.log( list[index],'list[index] list[index] list[index]');
      
      if(kc<1){
        wx.showModal({
          title: '提示',
          content: '该书籍库存暂时不足啦，请挑选其他感兴趣的书籍吧!',
          // success: function(res) {
          //   if (res.confirm) {
          //   console.log('用户点击确定')
          //   } else if (res.cancel) {
          //   console.log('用户点击取消')
          //   }
          // }
        })
      }else{
        if (already) {
          api.addcart({
            goodsid: ids,
            type:'BOOKS'
          }, res => {
            if (res.data.issuccess == 1) {
              list[index].already = already;
              wx.showToast({
                title: '添加成功',
              })
              cartids.push(ids);
              this.setData({
                list,
                cartids
              });
              wx.setStorageSync("cartids", cartids);
              app.badege(cartids);
            }
          });
        } else {
          api.delcart({
            ids
          }, res => {
            if (res.data.issuccess == 1) {
              list[index].already = already;
              wx.showToast({
                title: '取消成功',
              })
              let i = cartids.indexOf(ids);
              cartids.splice(i, 1);
              this.setData({
                list,
                cartids
              });
              wx.setStorageSync("cartids", cartids);
              app.badege(cartids);
            }
    
          })
        }
      }

  },

  getmorerecommend(clean) {
    if (clean){
      that.setData({list:[]})
    }
    let { start, pagesize,searchinput } = this.data;
    api.getmore({start,pagesize,keyword:searchinput }, res => {
      if (res.data.issuccess == 1) {
        let list = res.data.data;
        console.log( res.data.data,'res.data.data.lables')
        // console.log(start, 'start')
        this.formatdata((list),()=>{
          that.setData({ total: res.data.recommmendtotal, reachbtm: list.length == res.data.recommmendtotal, }, () => {
            that.getpage()
          })
        });
      }
    });
  },
  tosearch(e){
    this.setData({list:[],start:0},()=>{
      that.getmorerecommend();
    });
    // this.searchgoods(0);
  },
  // searchgoods(start){
  //   wx.showLoading({
  //     title: '加载中',
  //   })
  //   let { keyword, pagesize ,searchinput} = this.data;
  //   if (keyword == "") {
  //     wx.hideLoading();
  //     return;
  //   }
  //   api.searchgoods({ pagesize, start, keyword:searchinput }, res => {
  //     if (res.data.issuccess == 1) {
  //       let list = res.data.list, length = res.data.list.length;
  //       if (list.length == 0) {
  //         this.setData({ list: [], show: !0 });
  //         wx.hideLoading();
  //         return;
  //       }
  //       this.setData({ length, show: !1 });
  //       this.formatdata(list);
  //     }
  //   });
  // },
  // tosearch(e) {
  //   wx.navigateTo({
  //     url: '../search/search',
  //   })

  // },
  // tosearch(e) {
  //   let keyword = e.detail.value
  //   api.searchgoods(keyword, res => {
  //     if (res.data.issuccess == 1) {
  //       that.setData({
  //         list: []
  //       }, () => {
  //         console.log(res.data.list, 'res.data.list')
  //         that.formatlist(res.data.list, () => {
  //           console.log(list, 'list')
  //           that.setData({
  //             reachbtm: list.length == res.data.list.length
  //           })
  //         })
  //       })
  //     }
  //   })
  // },
  toseries(e) {
    let {
      id,
      type
    } = e.currentTarget.dataset;
    // console.log(id, "index", e);
    wx.navigateTo({
      url: '../series/series?t=' + type + '&&i=' + id,
    })
  },
  toage(e) {
    let {
      index
    } = e.currentTarget.dataset,
      url = `../agelist/agelist?i=${index}`;
    wx.navigateTo({
      url
    })
  },
  search(e) {
    this.setData({
      searchinput: e.detail.value
    })
    if(e.detail.value==''){
      that.setData({list:[]})
      that.getmain();
    }
  },
  formatdata(clist, reachbtm){
    let {
      list,
      cartids
    } = this.data, length = clist.length;
    // console.log(clist, "listlistlistlist");
    clist.forEach((x, i) => {
      // console.log(x,'clistrxxxxxx')
      // console.log(x.labels,'x.lablessss')
      
      if (cartids.indexOf(x.id) != -1) {
        clist[i].already = !0;
      }
      if (x.thumbPicPath.indexOf("http") == -1) {
        // console.log(111111,'11111')
        x.thumbPicPath = headimg + x.thumbPicPath;
      }
      if(x.labels){
        console.log(x.labels,'x.lables')
        x['labels'] = x.labels.split(',');
      }
      // if (x.detaillist.length > 0) {
      //   x.detaillist.forEach((y, i) => {
      //     if (y.indexOf("http") == -1) {
      //       x.detaillist[i] = headimg + x.detaillist[i];
      //     }
      //   });
      // }
    });
    list = list.concat(clist);
    this.setData({
      list,
      length
    },()=>{
      reachbtm()
    });
    wx.hideLoading();
  },
  todetail(e) {
    let {sendshow,hasphone}=that.data
    ,{isgetphone}=that.data
    // that.setData({sendshow:!0})
    if(!isgetphone){
      that.setData({sendshow:!0})
    }else{
      wx.navigateTo({
        url: '../books/detail/detail?i=' + e.currentTarget.dataset.id,
      }) 
    }
  },
  no(){
    that.setData({sendshow:!1})
  },
  /**
   * 获取数据
   */
  getmain() {
    console.log(app.logininfo,'info');
  },
  tomore(e) {
    let {
      type
    } = e.currentTarget.dataset;
    // console.log(type, "type", e);
    wx.navigateTo({
      url: '../works/works?t=' + type,
    })
  },
  // 选集
  isshow() {
    if (that.data.pageboxshow == !1) {
      that.setData({
        pageboxshow: !0
      })
    } else {
      that.setData({
        pageboxshow: !1
      })
    }
  },
  mod() {
    that.setData({
      pageboxshow: !1
    })
  },
  itemstart(e) {
    let { pagesize } = that.data, { pageindex } = e.currentTarget.dataset
    // console.log(pageindex,'pageindex')
    that.setData({
      start: pageindex * pagesize, pageboxshow: !1
    }, () => {
      // console.log(that.data.start,'itemstart-start')
      that.getmorerecommend(!0)
    })
    // console.log(e.currentTarget.dataset,'e.currentTarget.dataset')
  },
  getpage() {
    let { total, pagesize } = that.data, pagenumber, pageitem = [], left, right, item
    pagenumber = Math.ceil(total / pagesize)
    for (let i = 0; i < pagenumber; i++) {
      if (i != pagenumber - 1) {
        left = i * pagesize + 1
        right = i * pagesize + pagesize
        item = left + '~' + right
        pageitem.push({ item })
      } else {
        left = i * pagesize + 1
        right = total
        if (left == right) {
          item = left
        } else {
          item = left + '~' + right
        }
        pageitem.push({ item })
      }
    }
    that.setData({ pageitem })
    // console.log(pageitem, 'pageitem')
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {
    // console.log('onshow')
    let isgetphone=wx.getStorageSync('isgetphone')
    if(isgetphone){
      that.setData({isgetphone,hasphone:!0,sendshow:!1})
    }
    let cartids = wx.getStorageSync("cartids"),{list}=that.data;
    app.badege(cartids);
    list.forEach((x,i)=>{
      if (cartids.length>0){
        cartids.forEach((y,j)=>{
          if (cartids.indexOf(x.id)>-1){
            x.already = true;
          } else {
            x.already = false;
            return;
          }
    //       // if (y==x.id){
    //       //   x.already=true;
    //       // }else{
    //       //   return;
    //       // }
        })
      }else{
        x.already = false;
      }
    })
    that.setData({ cartids,list })
  
    // if (app.logininfo) {
    //   this.setData({
    //     currentpage: 1,
    //     length: 0,
    //     list: [],
    //     cartids: [],
    //   });
    //   that.getmain();
    // }
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {
    let { list, total, start, pagesize
      // currentpage,
      // length,
      // currentageindex
    } = this.data;
    if (start > total) {
      wx.showToast({
        icon: "none",
        title: '到底了',
      })
      return;
    }
    // start = pagesize * currentpage;
    // currentpage = currentpage + 1;

    this.setData({
      start: start + pagesize
      // currentpage
    },()=>{
      // console.log(start, 'onReachBottom-start')
      this.getmorerecommend();
    });
    // console.log(start, this.data.start);
  },
 
  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function() {
    return {
      title: app.logininfo.appletname,
      path: `pages/listen/listen?share=`+app.logininfo.userid,
    }
  }
})